package cn.huolabao.service;

import cn.huolabao.dto.UserDetailDto;
import cn.huolabao.feign.UserClient;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    private final UserClient userClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetailDto userDetailDto = userClient.getUserInfo(username);
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils
                .createAuthorityList(userDetailDto.getPerms().toArray(new String[0]));

        User user = new User(userDetailDto.getUsername()
                , userDetailDto.getPassword()
                , true, true
                , true, true
                , authorities);


        return user;
    }
}
